﻿#ifndef TCPSOCKET_H
#define TCPSOCKET_H

#include <memory>
#include <signalslot.h>

class WorkService;

class TcpSocket;

class REFLECTX_EXPORT TcpServer{
public:
    TcpServer();//workService用于回调需要,如果为空指针则信号将在不确定的线程中调用
    ~TcpServer();

    bool Bind(int port = 0,std::string ip = "");

    int GetPort() const;

    std::string GetHost() const;

    void Close();

    bool isActive() const;

    bool hasPendingConnection() const;

    TcpSocket* pendingConnection();

private:
    void RecvLoop();
    void UnRegister(TcpSocket* socket);
public:
    Signal<> NewConnection;

private:
    struct Private;
    std::unique_ptr<Private> _P;
    friend class TcpSocket;
};

class REFLECTX_EXPORT TcpSocket
{
private:
    struct PrivateCreate;
    TcpSocket(PrivateCreate* P);

public:
    TcpSocket();
    ~TcpSocket();

    bool isActive() const;
    std::string localHost() const;
    int localPort() const;

    std::string peerHost() const;
    int peerPort() const;

    bool Bind(int port = 0,std::string ip = "");
    bool ConnectTo(std::string ip,int port);
    void Close();

    int read(unsigned char* buffer,int len);
    ByteArray readAll();

    void write(const unsigned char* content,int len);
public:
    Signal<> Disconnected;
    Signal<> ReadyRead;

private:
    void RecvLoop();
    void _Close(bool wait);
private:
    struct Private;
    std::unique_ptr<Private> _P;

    friend class TcpServer;
};

#endif // TCPSOCKET_H
